package cn.glinks.liuhe.activity;

import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.glinks.liuhe.R;
import cn.glinks.liuhe.adpter.SearchResultAdapter;
import cn.glinks.liuhe.api.ApiConstants;
import cn.glinks.liuhe.api.ApiRequest;
import cn.glinks.liuhe.api.jsonbean.PersonalDetailsInfo;
import cn.glinks.liuhe.api.jsonbean.SearchResultInfo;
import cn.glinks.liuhe.api.jsonbean.UserInfo;
import cn.glinks.liuhe.app.AppApplication;
import cn.glinks.liuhe.app.AppConstant;
import cn.glinks.liuhe.base.BaseActivity;
import cn.glinks.liuhe.baserx.RxSubscriber;
import cn.glinks.liuhe.utils.ActTransAnimUtils;
import cn.glinks.liuhe.utils.GsonUtils;


/**
 * Des:搜索页面
 *
 * @author MarsBlade of Cyh
 * @created 2017-03-21 14:43
 */
public class SearchActivity extends BaseActivity {

    @BindView(R.id.iv_search)
    ImageView mSearchImageView;

    @BindView(R.id.btn_search)
    Button mSearchButton;

    @BindView(R.id.et_search)
    EditText mSearchEdit;

    @BindView(R.id.rv_result)
    RecyclerView mResultView;

    // 变量
    private UserInfo mUserInfo;
    private String mParkName = "";
    private String mSearch = "";
    private SearchResultAdapter mAdapter;
    private List<SearchResultInfo> mDataList = new ArrayList<>();

    @Override
    public int getLayoutId() {
        return R.layout.activity_search;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        // 加载用户信息
        mUserInfo = ((AppApplication) getApplicationContext()).getLoginUser();
        // 获取传递过来的数据
        Bundle bundle = this.getIntent().getExtras();
        mParkName = bundle.getString(AppConstant.BUNDLE_PARK_NAME, "");
        // 设置为透明状态栏
        SetTranslanteBar();
        // 初始化RecyclerView
        initRecyclerView();
        // 监听搜索输入框的变化
        setSearchEnable(false);
        mSearchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 0) {
                    setSearchEnable(false);
                } else {
                    setSearchEnable(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        // 监听搜索输入框的软键盘动作
        mSearchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mSearch = mSearchEdit.getText().toString().trim();
                    if (!mSearch.isEmpty()){
                        requestResult();
                    }
                    return true;
                }
                return false;
            }
        });
    }
    /*--------------------------------------------------------------------------------
     *                          初始化函数
     ---------------------------------------------------------------------------------*/
    /**
     * 请求获取搜索结果
     */
    private void initRecyclerView() {
        // 设置LayoutManager
        mResultView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        // 如果可以确定每个item的高度是固定的，设置这个选项可以提高性能
        mResultView.setHasFixedSize(true);
        // 设置默认的动画
        mResultView.setItemAnimator(new DefaultItemAnimator());
        // 创建并设置Adapter
        mAdapter = new SearchResultAdapter(mDataList);
        mResultView.setAdapter(mAdapter);
        // 设置item点击事件回调
        mAdapter.setOnItemClickListener(new SearchResultAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, SearchResultInfo info) {
                requestGetPersonalDetails(info);
            }
        });
    }

    /**
     * 请求获取搜索结果
     */
    private void requestResult() {
        // 发送网络请求, 请求获取园区建议数据
        mRxManager.add(ApiRequest.requestGetSearchName(mUserInfo.getJwt(), mParkName, mSearch)
                .subscribe(new RxSubscriber<String>(mContext) {
                    @Override
                    protected void _onNext(String msg) {
                        if (GsonUtils.getIntValue(msg, "error") == 0) {
                            String result = GsonUtils.getValue(msg, "result");
                            if (result != null && !result.isEmpty()) {
                                List<SearchResultInfo> list = (List<SearchResultInfo>)GsonUtils.fromJson(
                                        result,
                                        new TypeToken<List<SearchResultInfo>>(){}.getType());

                                mAdapter.setHighlightKey(mSearch);
                                mAdapter.clearItems();
                                for(int i=0;i<list.size();i++){
                                    mAdapter.addItem(list.get(i));
                                }
                            }
                        } else {
                            String reason = GsonUtils.getValue(msg, "reason");
                            ApiConstants.showError(reason);
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        // TODO:处理失败响应
                        //ToastUtils.showShort("获取搜索结果失败:" + message);
                    }
                }));
    }

    /**
     * 请求获取个人详细信息
     * @param info
     */
    private void requestGetPersonalDetails(SearchResultInfo info) {
        // 首先清空缓存
        ((AppApplication)getApplicationContext()).setPersonalDetailsInfo(null);
        // 发送网络请求, 请求获取个人详细信息
        mRxManager.add(ApiRequest.requestGetSearchPersonInfo(mUserInfo.getJwt(), info.getEmid())
                .subscribe(new RxSubscriber<String>(mContext) {
                    @Override
                    protected void _onNext(String msg) {
                        if (GsonUtils.getIntValue(msg, "error") == 0) {
                            String result = GsonUtils.getValue(msg, "result");
                            PersonalDetailsInfo info = (PersonalDetailsInfo) GsonUtils.fromJson(result, PersonalDetailsInfo.class);
                            ((AppApplication)getApplicationContext()).setPersonalDetailsInfo(info);
                            // 跳转到个人详细信息界面
                            ActTransAnimUtils.startActionSlideRightToLeft(SearchActivity.this, PersonalDetailsActivity.class);
                        } else {
                            String reason = GsonUtils.getValue(msg, "reason");
                            ApiConstants.showError(reason);
                        }
                    }

                    @Override
                    protected void _onError(String message) {
                        // TODO:处理失败响应
                        //ToastUtils.showShort("获取个人详细信息失败:" + message);
                    }
                }));
    }

    /**
     * 改变搜索按钮状态
     */
    private void setSearchEnable(boolean enable) {
        if (enable) {
            mSearchButton.setBackgroundResource(R.drawable.btn_search_green);
            mSearchButton.setTextColor(0xFF6BCCC6);
        } else {
            mSearchButton.setBackgroundResource(R.drawable.btn_search_gray);
            mSearchButton.setTextColor(0xFFBDBDBD);
        }
    }


    /*--------------------------------------------------------------------------------
     *                          点击事件接口实现
     ---------------------------------------------------------------------------------*/
    // 返回
    @OnClick(R.id.iv_back)
    public void clickBack() {
        ActTransAnimUtils.finishActionSlideLeftToRight(SearchActivity.this);
    }

    // 搜索
    @OnClick(R.id.btn_search)
    public void clickSearch() {
        mSearch = mSearchEdit.getText().toString().trim();
        if (!mSearch.isEmpty()){
            requestResult();
        }
    }

    /*--------------------------------------------------------------------------------
     *                          系统键处理
     ---------------------------------------------------------------------------------*/
    /**
     * 监听主页键,返回键
     *
     * @param keyCode
     * @param event
     * @return
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 返回
            ActTransAnimUtils.finishActionSlideLeftToRight(SearchActivity.this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
